<?php

/**
 * 订阅消息
 * @Author: Helloweba
 * @Date:   2020-01-01 20:24:57
 * @Last Modified by:   Helloweba
 * @Last Modified time: 2020-01-05 20:17:16
 */

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$exchange = 'topic.exchange';
$routerKey = 'sh.stock.deal'; //

$config = getConfig();
$connection = new AMQPStreamConnection(
    $config['host'],
    $config['port'],
    $config['user'],
    $config['password']
);

$channel = $connection->channel();

$channel->exchange_declare($exchange, 'topic', false, false, false);

// 为什么取消运行后queue也会消失

//$channel->queue_declare("topic.queue.a", false, false, true, false);
//$channel->queue_declare("topic.queue.b", false, false, true, false);
//$channel->queue_declare("topic.queue.c", false, false, true, false);
//
//$channel->queue_bind("topic.queue.a", $exchange, 'sh.#');
//$channel->queue_bind("topic.queue.b", $exchange, 'sz.*.deal');
//$channel->queue_bind("topic.queue.c", $exchange, '*.stock.deal');

echo " [*] Waiting for messages. To exit press CTRL+C" .PHP_EOL;
$callback = function ($msg) {
    //echo " Received message：", $msg->body, PHP_EOL;
    echo ' Received message：',$msg->delivery_info['routing_key'], ':', $msg->body, PHP_EOL;
    // sleep(1);  //模拟耗时执行
};
$channel->basic_consume("topic.queue.a", '', false, true, false, false, $callback);

while ($channel->is_consuming()) {
    $channel->wait();
}

$channel->close();
$connection->close();
